import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//1.导入组件
import login from '@/views/user/login.vue'
import layout from '@/views/user/layout.vue'
import home from '@/views/home/home.vue'
import movie from '@/views/movie/movie.vue'
import qa from '@/views/qa/qa.vue'
import user from '@/views/user/user.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import articleSearch from '@/views/home/articleSearch.vue'
import student from '@/views/user/student.vue'

//2.配置路由规则
const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      {
        name: 'home',
        path: '/home',
        component: home
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        meta: { isLogin: true }
      },
      {
        path: '/',
        redirect: '/home' // 重定向:重新指向其它path,会改变网址
      }
    ]
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'articleSearch',
    path: '/articleSearch',
    component: articleSearch
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  {
    name: 'student',
    path: '/student',
    component: student
  },
  {
    path: '*',
    redirect: '/notfound' // 重定向:重新指向其它path,会改变网址
  }
]

const router = new VueRouter({
  routes
})

//导入token工具包
import { getItem } from '@/utils/token.js'
//注册导航守卫  (跳转前执行)
router.beforeEach((to, from, next) => {
  //console.log(getItem)
  // to:目标路由. 要去哪里
  //  console.log(to)
  //from:来源路由. 从哪里来
  // console.log(from)
  //next():允许正常跳转

  //判断用户有没有登录
  //!getItem()没有登录的时候
  if (to.meta.isLogin && !getItem()) {
    //没有登录
    next({ path: '/login' })
  } else {
    //有登录,正常跳转
    next()
  }
})

export default router
